package com.zerui.manager.app.devicegroup.executer;

import com.alibaba.cola.catchlog.CatchAndLog;
import com.alibaba.cola.exception.BizException;
import com.zerui.cola.dto.Response;
import com.zerui.manager.devicegroup.DeviceGroup;
import com.zerui.manager.devicegroup.domainservice.DeviceGroupRepository;
import com.zerui.manager.web.cmd.DeviceGroupUpdateCmd;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author wh
 * @create_time 2023-08-23 16:29
 */
@Component
@CatchAndLog
public class DeviceGroupUpdateCmdExe {

    @Resource
    private DeviceGroupRepository deviceGroupRepository;

    public Response execute(DeviceGroupUpdateCmd deviceGroupUpdateCmd) {
        DeviceGroup root = deviceGroupRepository.selectById(deviceGroupUpdateCmd.getSupId());
        if(ObjectUtils.isEmpty(root) || !DeviceGroup.isRootName(root.getOrgName())){
            throw new BizException("上级节点必须是根节点");
        }
        DeviceGroup deviceGroup = deviceGroupRepository.selectById(deviceGroupUpdateCmd.getId());
        if(ObjectUtils.isEmpty(deviceGroup)){
            throw new BizException("节点不存在");
        }
        DeviceGroup group = deviceGroupRepository.getNodeByName(deviceGroupUpdateCmd.getOrgName());
        if(ObjectUtils.isNotEmpty(group) && !group.getId().equals(deviceGroupUpdateCmd.getId())){
            throw new BizException("节点名称重复");
        }
        deviceGroupRepository.update(
                DeviceGroup.create(
                    deviceGroup.getId(),
                    deviceGroupUpdateCmd.getOrgName(),
                    deviceGroupUpdateCmd.getSupId(),
                    deviceGroup.getDeviceIds(),
                    deviceGroup.getCreateTime(),
                        null
                )
        );
        return Response.buildSuccess();
    }

}
